package com.corx.network.mysqlstorage.handler;

import com.corx.network.core.handler.NetworkStateHandler;
import com.corx.network.core.type.NetworkStateEnum;
import com.corx.network.mysqlstorage.hub.DeviceRepositoryHub;
import com.corx.network.mysqlstorage.model.Network;
import lombok.extern.slf4j.Slf4j;

import java.util.Optional;

/**
 * @author gx
 * @version 1.0.0
 */
@Slf4j
public class JdbcNetworkStateHandler implements NetworkStateHandler {

    private final DeviceRepositoryHub hub;

    public JdbcNetworkStateHandler(DeviceRepositoryHub hub) {
        this.hub = hub;
    }

    @Override
    public void onChange(String networkId, NetworkStateEnum state) {
        if (networkId == null || networkId.isEmpty()) {
            log.warn("JdbcNetworkStateHandler处理器，接收到的networkId是空的 return，不做任何处理");
            return;
        }
        Optional<Network> optional = hub.networkRepo().findById(Long.parseLong(networkId));
        if (!optional.isPresent()) {
            log.warn("JdbcNetworkStateHandler处理器，根据设备networkId查询不到数据 return，不做任何处理");
            return;
        }
        Network network = optional.get();
        network.setState(state.getState());
        hub.networkRepo().update(network);
    }

}
